﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Sausage.Common;
using Sausage.Web.Domain;

namespace Sausage.Web.Models
{
    public class UserConfirmViewModel : IValidatableObject
    {
        public UserConfirmViewModel(){}

        public UserConfirmViewModel(Guid userID)
        {
            UserID = userID;
        }

        [Display(Name = "旧密码")]
        [Required(ErrorMessage = "请输入旧密码!")]
        [StringLength(32, ErrorMessage = "旧密码长度不超过32位!")]
        public string OldPassword { get; set; }

        [Display(Name = "新密码")]
        [Required(ErrorMessage = "请输入新密码!")]
        [StringLength(32, ErrorMessage = "新密码长度不超过32位!")]
        public string Password { get; set; }


        [Display(Name = "确认新密码")]
        [Required(ErrorMessage = "请再次输入新密码!")]
        [StringLength(32, ErrorMessage = "新密码长度不超过32位!")]
        public string PasswordAgain { get; set; }

        public Guid UserID { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> validationResultList = new List<ValidationResult>();
            
            if(Password != PasswordAgain)
            {
                ValidationResult validationResult = new ValidationResult("两次新密码输入不一致！");
                validationResultList.Add(validationResult);
            }

            if (Password.Length<4)
            {
                ValidationResult validationResult = new ValidationResult("密码长度必须大于4位！");
                validationResultList.Add(validationResult);
            }

            if(OldPassword == Password)
            {
                ValidationResult validationResult = new ValidationResult("新密码必须不同于默认密码！");
                validationResultList.Add(validationResult);
            }


            var user = UserHelper.GetUserByID(UserID);
            if (user == null ||
                !PasswordHash.Compare(OldPassword, user.Password))
            {
                ValidationResult validationResult = new ValidationResult("旧密码错误！");
                validationResultList.Add(validationResult);
            }
            
            return validationResultList;
        }

    }
}